<?php
load(array('cache', 'parser', 'sorter', 'style', 'config'));

function load($files = array()) {
	foreach ($files as $file) {
		include_once($file . '.php');
	}
}

$parser = new Parser();
$cache = new Cache(array(
		'duration' => $config['cache']['duration'],
		'directory' => $config['path'] . $config['cache']['directory'],
		'extension' => $config['cache']['extension']
	)
);

$planet = array();
foreach ($config['channels'] as $name => $channel) {
	if ($cache->deletable($name)) {
		$feed = file_get_contents($channel['link']);
		if (!empty($feed)) {
			$cache->write($name, $feed);
		}
	} else {
		$feed = $cache->read($name);
	}
	$planet = array_merge($planet, $parser->parse($feed));
}

$sorter = new Sorter();
$planet = $sorter->sort($planet, 'published');

if ($config['limit'] > 0) {
	$planet = array_slice($planet, 0, $config['limit']);
}

$style = new Style(array('style' => $config['style']));
$style->set('title', $config['title']);
$style->set('planet', $planet);
$style->set('channels', $config['channels']);

if ($cache->deletable($config['style'])) {
	$contents = $style->render();
	$cache->write($config['style'], $contents);
} else {
	$contents = $cache->read($config['style']);
}

echo $contents;
?>

